"""性能与通信开销测量工具（轻量模拟）。

提供计算时间测量和简单的通信大小估算。
"""
import time
import sys
from typing import Callable, Any, Dict


def measure_computation_cost(func: Callable, *args, repeat: int = 100, **kwargs) -> float:
	"""测量函数平均执行时间（毫秒）。"""
	if repeat <= 0:
		raise ValueError("repeat must be > 0")
	# 热身
	func(*args, **kwargs)
	start = time.perf_counter()
	for _ in range(repeat):
		func(*args, **kwargs)
	end = time.perf_counter()
	avg_sec = (end - start) / repeat
	return avg_sec * 1000.0


def measure_communication_cost(obj: Any) -> int:
	"""简单估算传输大小（字节）。"""
	if isinstance(obj, (bytes, bytearray)):
		return len(obj)
	if isinstance(obj, str):
		return len(obj.encode("utf-8"))
	# 对容器类型，尝试累加元素大小（递归）
	if isinstance(obj, (list, tuple, set)):
		total = 0
		for el in obj:
			total += measure_communication_cost(el)
		return total
	try:
		return sys.getsizeof(obj)
	except Exception:
		return 0


def benchmark(compare_funcs: Dict[str, Callable], sizes=(10, 100, 1000)) -> Dict[str, Dict[int, float]]:
	"""对比不同函数在不同规模下的平均执行时间。

	compare_funcs: 名称->可调用，调用时签名为 fn(n)
	sizes: 规模列表（示例用）
	返回 dict: {name: {size: ms}}
	"""
	results: Dict[str, Dict[int, float]] = {}
	for name, fn in compare_funcs.items():
		results[name] = {}
		for n in sizes:
			ms = measure_computation_cost(fn, n, repeat=20)
			results[name][n] = ms
	# 打印简单的 ASCII 表格方便观察
	# Header
	header = ["Function"] + [str(s) for s in sizes]
	rows = []
	for name, row in results.items():
		rows.append([name] + [f"{row[s]:.3f}" for s in sizes])

	# compute column widths
	cols = [header] + rows
	col_widths = [max(len(r[i]) for r in cols) for i in range(len(header))]
	# print header
	header_line = " | ".join(header[i].ljust(col_widths[i]) for i in range(len(header)))
	sep_line = "-+-".join("-" * col_widths[i] for i in range(len(header)))
	print(header_line)
	print(sep_line)
	for r in rows:
		print(" | ".join(r[i].ljust(col_widths[i]) for i in range(len(r))))

	return results

